package com.sf.dlb.service;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sf.dlb.bean.UserMessageBean;
import com.sf.dlb.constant.ResponseConstant;
import com.sf.dlb.jpa.model.UserInfo;
import com.sf.dlb.jpa.model.UserMessageInfo;
import com.sf.dlb.jpa.model.UserMessageStateInfo;
import com.sf.dlb.jpa.repository.UserInfoRepository;
import com.sf.dlb.jpa.repository.UserMessageRepository;
import com.sf.dlb.jpa.repository.UserMessageStateRepository;
import com.sf.dlb.mapper.dao.UserMessageMapper;
import com.sf.dlb.mapper.entity.UserMessageEntity;
import com.sf.dlb.utils.GsonUtils;
import com.sf.dlb.utils.ResultVOUtil;
import com.sf.dlb.utils.StateToValueUtils;
import com.sf.dlb.vo.PageVO;
import com.sf.dlb.vo.ResultVO;
import com.sf.dlb.vo.UserMessageVO;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**
 * Created by jing.tan on 2018/5/21.
 */
@Service
public class UserMessageService {
    private static Logger logger = LoggerFactory.getLogger(UserMessageService.class);
    @Autowired
    private UserMessageRepository userMessageRepository;
    @Autowired
    private UserMessageStateRepository userMessageStateRepository;
    @Autowired
    private UserMessageMapper userMessageMapper;
    @Autowired
    private UserInfoRepository userInfoRepository;

    /**
     * 保存消息
     */
    @Transactional
    public void saveUserMessage(String userId, String title, String type, String content){
        logger.info("saveUserMessage userId={},title={},content={}",userId,title,content);
        UserMessageInfo userMessageInfo=new UserMessageInfo();
        userMessageInfo.setTitle(title);
        userMessageInfo.setContent(content);
        userMessageInfo.setType(type);
        userMessageInfo.setSort("10");
        userMessageInfo.setUpdateDate(new Date());
        userMessageInfo.setCreateDate(new Date());
        userMessageInfo=userMessageRepository.save(userMessageInfo);
        //保存消息状态
        UserMessageStateInfo userMessageStateInfo=new UserMessageStateInfo();
        userMessageStateInfo.setUserId(userId);
        userMessageStateInfo.setMessageId(userMessageInfo.getId()+"");
        userMessageStateInfo.setState("1");
        userMessageStateInfo.setCreateDate(new Date());
        userMessageStateRepository.save(userMessageStateInfo);
    }
    /**
     * 用户消息列表
     */
    public ResultVO userMessageList(String userId,int type,int page, int size) {
        logger.info("userMessageList userId={},type={},page={},size={}", userId,type,page, size);
        PageHelper.startPage(page,size);
        List<UserMessageEntity>  userMessageEntities=new ArrayList<>();
        //0代表是查询全部消息
        if(type>0){
            userMessageEntities=userMessageMapper.findByUserIdAndTypeAndDelFlag(userId,type+"","0");
        }else{
            userMessageEntities=userMessageMapper.findByUserIdAndDelFlag(userId,"0");
        }
        PageInfo<UserMessageEntity> pageInfo=new PageInfo<>(userMessageEntities);
        List<UserMessageVO> userAppMessageVOS=new ArrayList<>();
        for (UserMessageEntity userMessageEntity:userMessageEntities) {
            UserMessageVO userAppMessageVO=new UserMessageVO();
            BeanUtils.copyProperties(userMessageEntity,userAppMessageVO);
            userAppMessageVO.setCreateDate(userMessageEntity.getCreateDate().getTime());
            userAppMessageVOS.add(userAppMessageVO);
        }
        PageVO pageVO = new PageVO();
        pageVO.setDataList(userAppMessageVOS);
        pageVO.setPageSize(size);
        pageVO.setCurrentPages(page);
        //当没有数据有显示有问题,pageInfo.isIsFirstPage(),pageInfo.isIsLastPage()
        pageVO.setFirstPage((!pageInfo.isHasPreviousPage()));//pageInfo.isHasPreviousPage()是否有上一页，
        pageVO.setLastPage((!pageInfo.isHasNextPage()));//pageInfo.isHasPreviousPage()是否有上一页
        pageVO.setTotalElements(pageInfo.getTotal());
        pageVO.setTotalPages(pageInfo.getPages());
        return ResultVOUtil.success(pageVO);
    }
    /**
     * 用户是否有最新消息
     * @return false=否 true=是
     */
    public boolean isLatestMessage(String userId){
        logger.info("isLatestMessage userId={}",userId);
        List<UserMessageStateInfo> userMessageInfos= userMessageStateRepository.findByUserIdAndState(userId,"1");
        if(CollectionUtils.isEmpty(userMessageInfos)){
            return false;
        }else{
            return true;
        }
    }
    /**
     * 用户消息更新-已读
     * @return
     */
    @Transactional
    public ResultVO userMessageUpdate(UserMessageBean userMessageBean){
        logger.info("userMessageUpdate userMessageBean={}", GsonUtils.getInstance().toJson(userMessageBean));
        String userId=userMessageBean.getUserId();
        String state=userMessageBean.getState();
        String id=userMessageBean.getId();
        String type=userMessageBean.getType();
        List<UserMessageStateInfo> userMessageStateInfos=new ArrayList<>();
        if(type.equals("1")){
            if(StringUtils.isEmpty(id)){
                return ResultVOUtil.error(ResponseConstant.ERROR,"消息编号不能为空");
            }
            UserMessageStateInfo userMessageStateInfo = userMessageStateRepository.findById(Long.valueOf(id));
            userMessageStateInfos.add(userMessageStateInfo);
        }else if(type.equals("2")){
            List<UserMessageStateInfo>  userMessageStateInfoList= userMessageMapper.findByUserIdAndTypeAndStateAndDelFlag(userId,"2","1","0");
            userMessageStateInfos.addAll(userMessageStateInfoList);
        }
        logger.info("userMessageUpdate userMessageStateInfos={}",userMessageStateInfos.size());
        if(CollectionUtils.isEmpty(userMessageStateInfos)){
            return ResultVOUtil.error(ResponseConstant.ERROR,"消息数据为空");
        }
        List<UserMessageStateInfo> userMessageStateUpdateInfos=new ArrayList<>();
        for (UserMessageStateInfo userMessageStateInfo:userMessageStateInfos) {
            userMessageStateInfo.setState("0");
            userMessageStateUpdateInfos.add(userMessageStateInfo);
        }
        userMessageStateRepository.save(userMessageStateUpdateInfos);
        return ResultVOUtil.success();
    }

    /**
     * 消息列表
     * @return
     */
    public ResultVO list(String type){
        logger.info("==list type={}",type);
        List<UserMessageEntity> userMessageEntities;
        if(StringUtils.isNotBlank(type)){
            userMessageEntities=userMessageMapper.findbyAllTypeMessage(type);
        }else{
            userMessageEntities=userMessageMapper.findbyAllMessage();
        }
        List<UserMessageVO> userMessageVOS=new ArrayList<>();
        for (UserMessageEntity userMessageEntity:userMessageEntities) {
            UserMessageVO userMessageVO=new UserMessageVO();
            BeanUtils.copyProperties(userMessageEntity,userMessageVO);
            userMessageVO.setTypeValue(StateToValueUtils.switchUserMessageValue(userMessageVO.getType()));
            if(StringUtils.equals(userMessageVO.getType(),"2")){
                userMessageVO.setUserIds("");
            }
            userMessageVO.setCreateDate(userMessageEntity.getCreateDate().getTime());
            userMessageVOS.add(userMessageVO);
        }
        return ResultVOUtil.success(userMessageVOS);
    }
    /**
     * 更新用户消息
     *
     */
    @Transactional
    public ResultVO update(UserMessageBean userMessageBean){
        logger.info("==update start userMessageBean="+GsonUtils.getInstance().toJson(userMessageBean));
        UserMessageInfo userMessageInfo= userMessageRepository.getOne(Long.valueOf(userMessageBean.getId()));
        if(null==userMessageInfo){
            return ResultVOUtil.error(ResponseConstant.ERROR,"数据不存在");
        }
        if(StringUtils.isNotBlank(userMessageBean.getType())){
            userMessageInfo.setType(userMessageBean.getType());
        }
        if(StringUtils.isNotBlank(userMessageBean.getTitle())){
            userMessageInfo.setTitle(userMessageBean.getTitle());
        }
        if(StringUtils.isNotBlank(userMessageBean.getContent())){
            userMessageInfo.setContent(userMessageBean.getContent());
        }
        userMessageInfo.setUpdateDate(new Date());
        userMessageRepository.save(userMessageInfo);
        return ResultVOUtil.success();
    }
    /**
     * 删除用户消息
     *
     */
    @Transactional
    public ResultVO delete(Long id){
        logger.info("==delete id={} ",id);
        UserMessageInfo userMessageInfo= userMessageRepository.getOne(id);
        if(null==userMessageInfo){
            return ResultVOUtil.error(ResponseConstant.ERROR,"数据不存在");
        }
        userMessageInfo.setDelFlag("1");
        userMessageInfo.setUpdateDate(new Date());
        userMessageRepository.save(userMessageInfo);
        //删除用户状态-物理删除
        List<UserMessageStateInfo> userMessageStateInfos=userMessageStateRepository.findByMessageId(id+"");
        userMessageStateRepository.delete(userMessageStateInfos);
        logger.info("delete userMessageStateInfos={}",userMessageStateInfos.size());
        return ResultVOUtil.success();
    }
    /**
     * 添加用户消息
     *
     */
    @Transactional
    public ResultVO add(UserMessageBean userMessageBean){
        logger.info("==add userMessageBean={} ",GsonUtils.getInstance().toJson(userMessageBean));
        UserMessageInfo userMessageInfo=new UserMessageInfo();
        BeanUtils.copyProperties(userMessageBean,userMessageInfo);
        userMessageInfo.setUpdateDate(new Date());
        userMessageInfo.setCreateDate(new Date());
        userMessageInfo=userMessageRepository.save(userMessageInfo);
        //消息状态添加; -1=所有用户；userid=指定用户
        ArrayList<UserMessageStateInfo> userMessageStateInfos=new ArrayList<>();
        if(userMessageBean.getUserIds().equals("-1")){
            List<UserInfo> userInfos=userInfoRepository.findAll();
            for (UserInfo info:userInfos) {
                UserMessageStateInfo userMessageStateInfo=new UserMessageStateInfo();
                userMessageStateInfo.setUserId(info.getUserId());
                userMessageStateInfo.setMessageId(userMessageInfo.getId()+"");
                userMessageStateInfo.setState("1");
                userMessageStateInfo.setCreateDate(new Date());
                userMessageStateInfos.add(userMessageStateInfo);
            }
        }else{
            String userIdStr=userMessageBean.getUserIds();
            String[] userIds=userIdStr.split(",");
            for (String str:userIds) {
                UserMessageStateInfo userMessageStateInfo=new UserMessageStateInfo();
                userMessageStateInfo.setUserId(str);
                userMessageStateInfo.setMessageId(userMessageInfo.getId()+"");
                userMessageStateInfo.setState("1");
                userMessageStateInfo.setCreateDate(new Date());
                userMessageStateInfos.add(userMessageStateInfo);
            }
        }
        logger.info("==add userMessageStateInfos={}",userMessageStateInfos.size());
        userMessageStateRepository.save(userMessageStateInfos);
        return ResultVOUtil.success();
    }
}
